﻿/*!
 * Knockout+ Library v1.1.0
 * https://knockoutplus.codeplex.com/
 *
 * Copyright 2014 Janusz Noszczyński and other contributors
 * Released under the MIT license
 * https://knockoutplus.codeplex.com/license
 *
 * More documentation and examples
 * http://blog.coderiseventures.com/
 */

(function ($, ko)
{
    ko.bindingHandlers.dateValue =
    {
        init: function (element, valueAccessor)
        {
            var $element = $(element);
            $element.addClass('date');

            $element.change(function ()
            {
                var val = $element.val();

                if (!val)
                {
                    //handle clearing input value
                    accessor.value(null);
                }
            });

            var accessor = valueAccessor();
            var val = ko.utils.unwrapObservable(accessor.value);
            var format = ko.utils.unwrapObservable(accessor.format);
            var lang = ko.utils.unwrapObservable(accessor.lang);

            var dp = $element.datepicker({ format: format, language: lang });
            var picker = $element.data("datepicker").picker;

            var dateVal = val ? new Date(val) : null;
            $element.datepicker('update', dateVal);

            accessor.value.subscribe(function (newValue)
            {
                var dateVal = newValue ? new Date(newValue) : null;
                $element.datepicker('update', dateVal);
            });            

            dp.on('changeDate', function (ev)
            {
                accessor.value(ev.date);
            });

            dp.on('show', function (ev)
            {
                picker.css("z-index", "9999");
            });
        }
    };
})
(jQuery, ko);